<template>

  <!-- 新增部门的弹层 -->
  <el-dialog :title="showTitle" :visible="showAddDlog" width="50%" @close="emptyFrom">
    <!-- 表单组件  el-form   label-width设置label的宽度   -->
    <!-- 匿名插槽 -->
    <el-form ref="addFormRef" label-width="120px" :model="formData" :rules="rules">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="formData.name" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="formData.code" style="width:80%" placeholder="1-50个字符" />
      </el-form-item>
      <el-form-item ref="formDataLabel" label="部门负责人" prop="manger">
        <el-select v-model="formData.manager" style="width:80%" placeholder="请选择" @focus="getEmployeesSimple">
          <el-option v-for="(item, index) in peoples" :key="index" :label="item.username" :value="item.username"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="formData.introduce" style="width:80%" placeholder="1-300个字符" type="textarea" :rows="3" />
      </el-form-item>
    </el-form>
    <!-- el-dialog有专门放置底部操作栏的 插槽  具名插槽 -->
    <el-row slot="footer" class="dialog-footer" type="flex" justify="center">
      <el-col>
        <el-button plain @click="emptyFrom">取消</el-button>
        <el-button type="primary" @click="onSubmit">确认</el-button>
      </el-col>
    </el-row>
  </el-dialog>

</template>

<script>
import { addDepartments, getDepartDateilById, getDepartmentTree, upDateDepartDateilById } from '@/api/departments'
import { getEmployeesSimple } from '@/api/employees'
export default {
  name: 'AddDepts',
  components: {},
  props: {
    showAddDlog: {
      type: Boolean,
      required: true
    },
    treeNode: {
      type: Object,
      required: true
    }
  },

  data() {
    const checNameRepeat = async(rule, value, callback) => {
      // 要添加的部门名称不能和兄弟部门相同
      // value 是要添加到部门的名称
      // 兄弟部门
      // 方式1 取当前部门的children
      // if (!this.treeNode.children) return callback()
      // const borthers = this.treeNode.children
      // const f = borthers.find(t => t.name === value)
      // if (f) {
      //   callback(new Error('存在相同名称的兄弟部门'))
      // } else {
      //   callback()
      // }

      // 方式2 通过请求获取所有部门 然后再找兄弟部门
      const { depts } = await getDepartmentTree() // 获取所有部门
      let borther
      if (this.formData.id) {
        // 编辑
        // 找到所有同级部门
        borther = depts.filter(t => t.pid === this.treeNode.pid && t.id !== this.treeNode.id)
      } else {
        // 新增
        borther = depts.filter(t => t.pid === this.treeNode.id)
        console.log(borther, this.treeNode)
      }
      const id = borther.find(i => i.name === value)
      if (id) {
        callback(new Error('存在相同名称的兄弟部门'))
      }
    }
    // 判断是否code重名
    const checCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartmentTree()
      if (this.formData.id) {
        // 编辑
        const borther = depts.filter(t => t.pid === this.treeNode.pid && t.id !== this.treeNode.id)
        if (borther.some(t => t.code === value)) {
          callback(new Error('存在相同编号的兄弟部门'))
        } else {
          callback()
        }
      }
      if (depts.some(t => t.code === value)) {
        callback(new Error('存在相同编号的兄弟部门'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 验证规则
      rules: {
        name: [{ required: true, message: '请输入部门名称', trigger: 'blur' }, { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }, { validator: checNameRepeat, trigger: 'blur' }], // 部门名称
        code: [{ required: true, message: '请输入部门编码', trigger: 'blur' }, { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }, { validator: checCodeRepeat, trigger: 'blur' }], // 部门编码
        manager: [{ required: true, message: '请选择部门管理者', trigger: 'blur' }], // 部门管理者
        introduce: [{ required: true, message: '请输入部门介绍', trigger: 'blur' }, { min: 1, max: 300, message: '长度在 1 到 300 个字符', trigger: 'blur' }] // 部门介绍
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑子部门' : '新增子部门'
    }
  },
  created() {

  },
  methods: {
    async getEmployeesSimple() {
      this.peoples = await getEmployeesSimple()
    },
    onSubmit() {
      this.$refs.addFormRef.validate(async isok => {
        if (isok) {
          if (this.formData.id) {
            // 编辑
            await upDateDepartDateilById(this.formData)
          } else {
            // 新增
            await addDepartments({
              ...this.formData,
              pid: this.treeNode.id
            })
          }
          this.$message.success('更新成功!')
          // 通知父组件更新树形列表
          this.$emit('addDepartment')
          // 通知父组件关闭弹层
          this.$emit('update:showAddDlog', false)
        }
      })
    },
    emptyFrom() {
      // this.formData = {}
      this.$emit('update:showAddDlog', false)
      // 第二种方法 实用elmentui 的方法 清除表单
      this.formData = this.$options.data().formData
      this.$refs.addFormRef.resetFields() // 清空表单并移除验证
    },
    async getDepartDateilById(id) {
      const formData = await getDepartDateilById(id)
      this.formData = formData
    }
  }
}
</script>

<style lang="less" scoped>

</style>
